<?php
App::uses('AppModel', 'Model');

class Menus extends AppModel {
/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'name';
	public $actsAs = array('Tree');
/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		"name"=>array( 
                        "unique"=>array( 
                                "rule"=>array("checkUnique", array("slug", "domain_id")), 
                                "message"=>"A link with that name already exists for that institution" 
                        ) 
                ),
		'slug' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);

	public $hasAndBelongsToMany = array(
			'Domain' => array(
				'className' => 'Domain',
				'joinTable' => 'domains_menuses',
				'foreignKey' => 'menus_id',
				'associationForeignKey' => 'domain_id',
				'unique' => 'keepExisting',
				'conditions' => '',
				'fields' => '',
				'order' => '',
				'limit' => '',
				'offset' => '',
				'finderQuery' => '',
				'deleteQuery' => '',
				'insertQuery' => ''
	)
	);
	
	public $hasMany = array(
		'Article' => array(
			'className' => 'Article',
			'foreignKey' => 'menuses_id',
			'conditions' => '',
			'fields' => array('Article.slug'),
			'order' => '',
			'conditions' => array('Article.slug <>'=>null)
		)
	);
	
	public $belongsTo = array(
			'Upload' => array(
					'className' => 'Upload',
					'foreignKey' => 'upload_id',
					'conditions' => '',
					'fields' => '',
					'order' => ''
			)
	);
	
	// nadpisanie funkcji sprawdzajacej unikid dwoch kolumn
	function checkUnique($data, $fields) {
		$domain_id = Configure::read('Config.domain.id');
		$this->Domain->id = $domain_id;
		$options['joins'] = array(
		array('table' => 'domains_menuses',
							'alias' => 'DomainsMenus',
							'type' => 'inner',
							'conditions' => array(
									'Menus.id = DomainsMenus.menus_id'
		)
		),
		array('table' => 'domains',
							'alias' => 'Domain',
							'type' => 'inner',
							'conditions' => array(
									'DomainsMenus.domain_id = Domain.id'
		)
		)
		);
		$options['conditions'] = array(
					'Menus.slug'=>$this->data['Menus']['slug'],
					'Domain.id'=>$domain_id
		);
		$link = $this->find('list',$options);
	
		return (count($link) <= 1 ) ? true : false;
	}
	
	
	public function beforeDelete($cascade = true) {
		$count = $this->Article->find("count", array(
	        "conditions" => array("menuses_id" => $this->id)
		));
		if ($count == 0) {
			return true;
		} else {
			return false;
		}
	}
}
